﻿using Orchard.ContentManagement;
using Orchard.Data;
using Orchard.Recipes.Models;
using Orchard.Recipes.Services;
using System;
using Vitus.MediaProcessing.Models;

namespace Vitus.MediaProcessing.ImportExport
{
    public class MediaProfileAttachmentsRecipeHandler : IRecipeHandler
    {
        private readonly IRepository<MediaProfileAttachmentRecord> mediaProfileAttachmentRepository;
        private readonly IContentManager contentManager;

        public MediaProfileAttachmentsRecipeHandler(
            IRepository<MediaProfileAttachmentRecord> mediaProfileAttachmentRepository,
            IContentManager contentManager)
        {
            this.mediaProfileAttachmentRepository = mediaProfileAttachmentRepository;
            this.contentManager = contentManager;
        }

        public void ExecuteRecipeStep(RecipeContext recipeContext)
        {
            if (!String.Equals(recipeContext.RecipeStep.Name, "MediaProfileAttachments", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            foreach (var attachmentDefinitionElement in recipeContext.RecipeStep.Step.Elements())
            {
                var contentItem = this.contentManager.ResolveIdentity(new ContentIdentity(attachmentDefinitionElement.Attribute("MediaProfileAttachmentsPartRecord_Identity").Value));

                if (contentItem != null)
                {
                    var attachment = new MediaProfileAttachmentRecord
                    {
                        MediaProfileAttachmentsPartRecord = new MediaProfileAttachmentsPartRecord { Id = contentItem.Id },
                        MediaPath = attachmentDefinitionElement.Attribute("MediaPath").Value,
                        ProfileName = attachmentDefinitionElement.Attribute("ProfileName").Value
                    };

                    this.mediaProfileAttachmentRepository.Create(attachment);
                }
            }

            recipeContext.Executed = true;
        }
    }
}
